/*
 * Copyright 2004 original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jbfilter.jsp;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.jsp.tagext.DynamicAttributes;

/**
 * Support for classes that implement the {@link DynamicAttributes} interface.
 * @author Marcus Adrian
 */
public class DynamicAttributesSupport implements DynamicAttributes {

	private Map<String, Object> dynAttrs = Collections.emptyMap(); 
	@Override
	public void setDynamicAttribute(String uri, String localName, Object value) {
		if (dynAttrs.isEmpty()) {
			dynAttrs = new HashMap<String, Object>();
		}
		dynAttrs.put(localName, value);
	}
	public Map<String, Object> getDynamicAttributes() {
		return dynAttrs;
	}
	/**
	 * For type safety a assignable class for the return value is specified. If it doesn't match
	 * an explicit {@link ClassCastException} is thrown.
	 * @param <T> the return value's expected type
	 * @param key the key the value is mapped to
	 * @param clazz a assignable class for the return value
	 * @throws ClassCastException
	 * @return the value if found, otherwise {@code null}
	 */
	public <T> T  getDynamicAttribute(String key, Class<T> clazz) {
		if (clazz == null) {
			throw new NullPointerException("clazz is null.");
		}
		Object found = dynAttrs.get(key);
		if (found == null) {
			return null;
		}
		if (found.getClass().isAssignableFrom(clazz)) {
			@SuppressWarnings("unchecked")
			T foundAsT = (T)found;
			return foundAsT;
		} else {
			throw new ClassCastException(
					String.format("%s is not assignable to %s.",
							found.getClass().getName(), clazz.getName()));
		}
	}
}
